var userDataPageSize = 20;

function createList(pageNo = 1, pageSize = 10) {

    var start = (pageNo - 1) * pageSize;
    apiAdminGetRecord('adminModel', start, pageSize, { 'createTime': { $ne: 0 } }, function (data) {
        if (data.code === 0) {
            if (data.code === 0) {
                setTimeout(() => {
                    $('#dataList').bootstrapTable('load', data.msg);
                }, 100)
            }
        }
    });
}

function addAccount(account, password, nickname, permission = -1, cb) {


    apiAdminGetRecord('adminModel', 0, 1, { account: account }, function (data) {
        if (data.code === 0) {
            if (data.code === 0 && data.msg && data.msg.recordArr.length >= 1) {
                $.modal({ body: '账户已存在' });
                return;
            } else {
                let saveData = {
                    account: account,
                    password: password,
                    nickname: nickname,
                    permission: permission,
                    createTime: Date.now()
                };
                apiAdminAddRecord('adminModel', saveData, function (data) {
                    if (data.code === 0) {
                        $("#nickname").val('');
                        $("#account").val('');
                        $("#password").val('');
                        $.modal({ body: '新增成功' });
                        createList();
                    }
                })
            }
        }
    });

}

function deleteAccount(uid) {
    Swal.fire({
        title: '确定删除该管理员吗？',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#198754',
        cancelButtonColor: '#d93444',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then((result) => {
        if (result.isConfirmed) {
            apiAdminDeleteRecord('adminModel', { uid: uid }, function () {
                createList();
            })
        }
    })

}




$(document).ready(function () {
    //数据表格初始化
    $('#dataList').bootstrapTable({
        showRefresh: true,
        striped: true, // 是否显示行间隔色
        pageNumber: 1, // 初始化加载第一页
        pagination: true, // 是否分页
        sidePagination: 'server', // server:服务器端分页|client：前端分页
        pageSize: 10, // 单页记录数
        pageList: [10, 20, 30],
        theadClasses: "thead-light",//这里设置表头样式
        totalField: "totalCount",
        smartDisplay: false,
        dataField: "recordArr",
        maintainSelected: true,
        buttonsClass: 'light',
        buttonsPrefix: 'btn',
        showRefresh: false,// 刷新按钮
        onPageChange: function (number, size) {
            createList(number, size);
        },
        onPostBody: function () {
            //重新启用弹出层,否则formatter格式化函数返回的html字符串上的tooltip提示不生效
            $('[data-bs-toggle="tooltip"]').each(function (i, el) {
                new bootstrap.Tooltip(el)
            })
        },
        onLoadSuccess: function () {
            //重新启用弹出层,否则formatter格式化函数返回的html字符串上的tooltip提示不生效
            $('[data-bs-toggle="tooltip"]').each(function (i, el) {
                new bootstrap.Tooltip(el)
            })
        },
        queryParams: function (params) { // 上传服务器的参数
            var temp = {//如果是在服务器端实现分页，limit、offset这两个参数是必须的
                limit: params.limit, // 每页显示数量
                offset: params.offset, // SQL语句起始索引
            };
            return temp;
        },
        columns: [{
            title: 'id',
            field: '_id',
            visible: false
        },
        {
            title: '管理员ID',
            width: 200,
            align: "center",
            valign: "middle",
            field: 'uid',
        }, {
            title: '管理员账号',
            width: 200,
            align: "center",
            valign: "middle",
            field: 'account',

        }, {
            title: '管理员权限',
            width: 200,
            align: "center",
            valign: "middle",
            field: 'permission',
            formatter: permissionMatter

        }, {
            title: '管理员昵称',
            width: 200,
            align: "center",
            valign: "middle",
            field: 'nickname',

        },
        // {
        //     title: '权限',
        //     align: "center",
        //     valign: "middle",
        //     field: 'permission',
        //     sortable: true,
        //     formatter: permissionMatter
        // },
        {
            title: '创建时间',
            width: 200,
            align: "center",
            valign: "middle",
            field: 'createTime',
            formatter: function (value) {
                return new Date(value).toLocaleString();
            }
        },
        {
            title: '操作',
            width: 200,
            align: "center",
            valign: "middle",
            formatter: option
        }]
    });
    $('#dataList').bootstrapTable('hideLoading');
    createList(1);
});



// 定义删除、更新按钮
function option(value, row, index) {
    var htm = "";
    htm += `<button type="button" class="btn btn-light"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="删除账号" onClick="deleteAccount(${row.uid})"><i class="bi bi-trash3-fill fs-5 text-danger"></i></button>`;
    // htm += `<button type="button" class="btn btn-danger btn-sm" onClick="deleteAccount(${row.uid})">删除</button>`;
    return htm;
}

function addNew() {

    $('#addNewAdmin').modal('show');
}

function saveAdmin() {

    var nickname = $("#nickname").val();
    if (!nickname || nickname.length === 0) {
        Swal.fire('请输入昵称');
        return;
    }
    var account = $("#account").val();
    if (!account || account.length === 0) {
        Swal.fire('请输入帐号');
        return;
    }

    var password = $("#password").val();
    if (!password || password.length === 0) {
        Swal.fire('请输入密码');
        return;
    }

    let permission = $("#permission").val();

    // var permission = 0;
    // if ($("#userManager")[0].checked) {
    //     permission |= enumeration.userPermissionType.USER_MANAGER;
    // }
    // if ($("#systemManager")[0].checked) {
    //     permission |= enumeration.userPermissionType.USER_SYSTEM_MANAGER;
    // }
    // if ($("#spreadManager")[0].checked) {
    //     permission |= enumeration.userPermissionType.SPREAD_MANAGER;
    // }
    // if ($("#dataManager")[0].checked) {
    //     permission |= enumeration.userPermissionType.DATA_MANAGER;
    // }
    // if ($("#gameControl")[0].checked) {
    //     permission |= enumeration.userPermissionType.GAME_CONTROL;
    // }

    addAccount(account, password, nickname, permission);

    $('#addNewAdmin').modal('hide');
}

function permissionMatter(value, row, index) {


    if (value == -1) {
        return '系统管理员'
    } else if (value == 428) {
        return '普通管理员'
    } else if (value == 4) {
        return '代理权限'
    } else {
        return '未知'
    }

    // let userManagerCK = (permission & enumeration.userPermissionType.USER_MANAGER) !== 0 ? 'checked' : null;
    // let systemManagerCK = (permission & enumeration.userPermissionType.USER_SYSTEM_MANAGER) !== 0 ? 'checked' : null;
    // let dataManagerCK = (permission & enumeration.userPermissionType.DATA_MANAGER) !== 0 ? 'checked' : null;
    // let spreadManagerCK = (permission & enumeration.userPermissionType.SPREAD_MANAGER) !== 0 ? 'checked' : null;
    // let gameControlCK = (permission & enumeration.userPermissionType.GAME_CONTROL) !== 0 ? 'checked' : null;
    // var htm = "";
    // htm += `<div class="form-check form-check-inline"><input class="form-check-input" ` + userManagerCK + `  type="checkbox"  value="option1">
    // <label class="form-check-label" for="inlineCheckbox1">用户管理</label></div>`;
    // htm += `<div class="form-check form-check-inline"><input class="form-check-input" ` + systemManagerCK + ` type="checkbox"  value="option1">
    // <label class="form-check-label" for="inlineCheckbox1">系统维护</label></div>`;
    // htm += `<div class="form-check form-check-inline"><input class="form-check-input" ` + spreadManagerCK + ` type="checkbox"  value="option1">
    // <label class="form-check-label" for="inlineCheckbox1">联盟管理</label></div>`;
    // htm += `<div class="form-check form-check-inline"><input class="form-check-input" ` + dataManagerCK + ` type="checkbox"  value="option1">
    // <label class="form-check-label" for="inlineCheckbox1">数据统计</label></div>`;
    // htm += `<div class="form-check form-check-inline"><input class="form-check-input" ` + gameControlCK + ` type="checkbox"  value="option1">
    // <label class="form-check-label" for="inlineCheckbox1">控制管理</label></div>`;
    // return htm;

}
